/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlcommand;

import data.ManagerDatabase;
import data.Row;
import data.Table;
import java.util.ArrayList;

/**
 *
 * @author Quang
 */
public class Delete extends Command{
    private String conditions;
    private String tableName;
    public Delete(String strSQL, ManagerDatabase md){
        super(strSQL,md);
    }
    
   
    @Override
    public Command getCommand(MyError err){
        StringBuffer strBuff = new StringBuffer(this.sql);
        int posDelete = Command.indexOfString(strBuff, "DELETE");
        int posFrom = Command.indexOfString(strBuff,"FROM");
        if(posDelete!=0 || posFrom !=7){
            err.setError("Error!! khong co tu khoa DELETE hoac FROM");
            return null;
        }
        
        int posWhere = Command.indexOfString(strBuff, "WHERE");
        if(posWhere ==-1){//ko co dieu kien
            tableName  = strBuff.substring(posFrom + 5, strBuff.length());
        }
        else{//co dieu kien
            tableName = strBuff.substring(posFrom +5, posWhere);
            conditions = strBuff.substring(posWhere+6,strBuff.length());
        }
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT * FROM ").append(tableName);
        if(conditions != null){
            sb.append(" WHERE ").append(conditions);
        }
        return new Select(sb.toString(), manager);        
       
       
    }
     @Override
    public  ArrayList<Row> excute(MyError err){
         Select select = (Select)this.getCommand(err);
         ArrayList<Row> rows = select.excute(err);
         if(rows == null){
             return null;
         }
         tableName = Command.ChuanHoa(tableName);
         Table table = manager.getTable(tableName);
         if(table==null){
             err.setError("Error!! Khong tim thay ten bang");
             return null;
         }
             
         for(int i=0; i<rows.size();i++){
             if(!table.deleteRow(rows.get(i)))
                 return null;
         }
        return rows;
    }
}
